<?php
/**
 * Passport.class.php
 *
 */

namespace MobileApi;

use Center\MemberScale;
use Circle\Circle;
use Mobile\RecomData;
use Notice\RedDot;
use Passport\Login;
use Encrypt\Blowfish;
use Center\User as CUser;
use Mobile\AddPushTag;
use Center\DeviceBind;

/**
 *
 * 通行证库
 *
 * @ignore
 * @package MobileApi
 * @author  suning <snsnsky@gmail.com>
 *
 */
class Passport
{
    const LOGIN_TYPE_REG = 0;
    const LOGIN_TYPE_LOGIN = 1;

    /**
     * 登录
     *
     * @param string $name 用户名
     * @param string $pwd  密码
     * @return array
     */
    public static function login($name, $pwd)
    {
        $pwd = Login::decodePassword($pwd);
        if (empty($pwd)) {
            return [203, '您输入的手机号或密码有误'];
        }
        $ret = Login::doLogin($name, $pwd, false);
        if (!empty($ret['UserId'])) {
            $result = self::getLoginInfo($ret['UserId'], 1);

            return [200, $result];
        }

        return [$ret['status'], $ret['msg']];
    }

    /**
     * 获取SSID, 并开启session
     *
     * @param array  $user      用户信息
     * @param string $device_id 设备ID
     * @return string
     */
    public static function getSSID($user, $device_id)
    {
        $pwd_hash = sprintf("%u", crc32($user['Password']));
        $str = sprintf('%s|%s|%s|%s', sprintf("%u", crc32(trim($device_id))), $user['UserId'], $pwd_hash,
            (int)$user['LoginCount']);
        $ssid = self::encode($str);
        session_id($ssid);
        session_start();

        $_SESSION['uid'] = $user['UserId'];
        $_SESSION['pwd_crc'] = $pwd_hash;
        $_SESSION['login_count'] = $user['LoginCount'];

        return $ssid;
    }

    /**
     * 返回标准用户登录信息
     *
     * @param int $userId 用户Id
     * @param int $type   区别登录与注册以返回不同信息 0：注册 1：登录
     * @return array
     */
    public static function getLoginInfo($userId, $type = self::LOGIN_TYPE_REG)
    {
        $user = CUser::getInfoByIds($userId);
        // 覆盖通行证的
        $birthday = '';
        if (!empty($user[CUser::FIELD_BIRTHDAY]) && $user[CUser::FIELD_BIRTHDAY] != '0000-00-00') {
            $birthday = (string)$user[CUser::FIELD_BIRTHDAY];
        }
        $result = [
            'Auth' => self::getSSID($user, trim($_GET['deviceid'])),
            'UserId' => (int)$user[CUser::FIELD_USER_ID],
            'CityId' => (int)$user[CUser::FIELD_CITY_ID],
            'CityName' => (string)$user[CUser::FIELD_CITY_NAME],
            'Sex' => $user[CUser::FIELD_SEX],
            'UserNick' => $user[CUser::FIELD_USER_NICK],
            'RealName' => $user[CUser::FIELD_REAL_NAME],
            'IdCode' => $user[CUser::FIELD_ID_CODE],
            'HeadUrl' => $user[CUser::FIELD_HEAD_URL],
            'Mobile' => $user[CUser::FIELD_MOBILE],
            'BirthDay' => $birthday,
            'JCoinNum' => (int)$user[CUser::FIELD_J_COIN],
            'IsTop' => (int)$user[CUser::FIELD_IS_SHOP],
        ];
        $red_dot = RedDot::getDot($user[CUser::FIELD_USER_ID]);
        $result['NoticeRedDot'] = 0;
        if (!empty($red_dot[$user[CUser::FIELD_USER_ID]])) {
            $result['NoticeRedDot'] = 1;
        }

        $result['Document'] = loadconf('user/document')['document'];

        // 自动更新设备用户关系
        if ($GLOBALS['g_appid'] != MOBILE_APPID_WEB) {
            $info = Device::getDeviceInfo($GLOBALS['g_appid'], $GLOBALS['g_deviceid']);
            if ($info['Id'] && $info['UserId'] != $user['UserId']) {
                $ios_token = isset($info['iOSToken']) ? $info['iOSToken'] : '';
                Device::initDevice($GLOBALS['g_appid'], $GLOBALS['g_deviceid'], $info['Channel'], $info['Token'],
                    $user['UserId'], $ios_token);
            }
        }

        if (!empty($info['Token'])) { // 打上登录标签 同时会自动打上环境标签 DEV|ONLINE
            AddPushTag::addTag($info['Token'], AddPushTag::TAG_LOGIN);
        }

        return $result;
    }

    /**
     * 登陆认证信息加密
     *
     * @param string $str 加密内容
     * @param string $key 加密密钥
     * @return string
     */
    public static function encode($str, $key = __KEY__)
    {
        return Blowfish::encode($str, $key);
    }

    /**
     * 登陆认证信息解密
     *
     * @param string $str 待解密内容
     * @param string $key 解密密钥
     * @return bool|array           成功返回解密内容, 失败返回false
     */
    public static function decode($str, $key = __KEY__)
    {
        $decode = Blowfish::decode($str, $key);

        if ($decode != false) {
            $arr = explode('|', $decode);
            if (count($arr) == 4) {
                if ($arr[0] == sprintf("%u", crc32(trim($_GET['deviceid']))) && is_numeric($arr[1])) {
                    return ['uid' => $arr[1], 'pwd_hash' => $arr[2], 'login_count' => (int)$arr[3]];
                }
            }
        }

        return false;
    }
}